package com.qian2.pricesharingapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


import com.example.lb2.JSONParser;
import com.example.pricesharingapplication.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;



public class AllProductsActivity extends ListActivity {

	// Check if there is a network connection
	public boolean isOnline() {
		ConnectivityManager cm =
				(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	public static final String Email = "emailKey";
	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	//ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String, String>>();;

	// url to get all products list
	private static String url_all_products = "http://wwwfyp.cse.ust.hk:7117/get_all_products.php";

	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCTS = "Item";
	private static final String TAG_upc = "upc";
	private static final String TAG_ID = "categoryID";
	private static final String TAG_NAME = "name";
	private static final String TAG_UID = "uid";
	private static final String TAG_BRAND = "brand";
	int success =0;
	boolean refreshing=false;
	// products JSONArray
	JSONArray products = null;
	ArrayList<String> product_list = new ArrayList<String>();
	private MainArrayAdapter madapter;
	//	ArrayList<NewsItem> results = new ArrayList<NewsItem>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pull_to_refresh);
		//        ActionBar actionBar = getActionBar(); 
		//        actionBar.show(); 

		// Set a listener to be invoked when the list should be refreshed.
		((MainActivity) getParent()).temp(this);
		((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				// Do work to refresh the list here.
				creatlist();
			}
		});

		creatlist();
	}

	public void creatlist() {

		// Hashmap for ListView

		// Loading products in Background Thread
		if (refreshing==true) return;
		refreshing=true;



		new LoadAllProducts().execute();



		// Get listview
		ListView lv = getListView();

		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String uid = ((TextView) view.findViewById(R.id.uid)).getText()
						.toString();
				String brand = ((TextView) view.findViewById(R.id.brand)).getText()
						.toString();
	
				if (!brand.equals("Server_error") && !brand.equals("No_network")){
					// Starting new intent
					Intent in = new Intent(getApplicationContext(),
							ProductPage.class);
					// sending upc to next activity
					in.putExtra(TAG_UID, uid);

					// starting new activity and expecting some response back
					startActivityForResult(in, 100);
				}

			}
		});
	}

	// Response from Edit Product Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received 
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}

	}

	/**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	class LoadAllProducts extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */


		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			((PullToRefreshListView) getListView()).prepareForRefresh();
			((PullToRefreshListView) getListView()).smoothScrollToPosition(0);
		}

		/**
		 * getting All products from url
		 * */
		ListAdapter adapter2;
		protected String doInBackground(String... args) {

			// Building Parameters
			if (product_list.isEmpty()){
				runOnUiThread(new Runnable() {
					public void run() {

						madapter = new MainArrayAdapter(AllProductsActivity.this, product_list){

							@Override
							public View getView(int position, View convertView,
									ViewGroup parent) {
								// TODO Auto-generated method stub
								View view= super.getView(position, convertView, parent);

								Button button=(Button) view.findViewById(R.id.report_price_button);
								button.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										// TODO Auto-generated method stub
										if(!MainActivity.sharedpreferences.contains(Email)){
											Intent in2 = new Intent(getApplicationContext(),
													ChooseAccount.class);
											startActivityForResult(in2, 90);
											
										}
										else{
											Intent in = new Intent(AllProductsActivity.this,QuotationActivity.class);
											// sending upc to next activity
											in.putExtra(TAG_UID, (CharSequence) ((TextView)((View) v.getParent()).findViewById(R.id.uid)).getText().toString());
											in.putExtra(TAG_NAME, (CharSequence) ((TextView)((View) v.getParent()).findViewById(R.id.name)).getText().toString());
											startActivityForResult(in, 100);
										}

									}

								});
								return view;
							}

						};
						setListAdapter(madapter);
					
					}
				});
				((PullToRefreshListView) getListView()).prepareForRefresh();
				((PullToRefreshListView) getListView()).smoothScrollToPosition(0);
			}



			product_list = new ArrayList<String>();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			// getting JSON string from URL
			//TODO (All product)gett data from database but not from network
			JSONObject json=null;
			if(isOnline())
				json = jParser.makeHttpRequest(url_all_products, "GET", params);
			System.out.println(json);

			try {
				success=0;
				// Checking for SUCCESS TAG
				if (isOnline() && json!=null){
					success = json.getInt(TAG_SUCCESS);
					if (success == 1 ) {
						// products found
						// Getting Array of Products
						products = json.getJSONArray(TAG_PRODUCTS);

						// looping through All Products
						for (int i = 0; i < products.length(); i++) {
							JSONObject c = products.getJSONObject(i);

							// Storing each json item in variable
							String uid = c.getString(TAG_UID);
							c.getString(TAG_upc);
							c.getString(TAG_ID);
							String name = c.getString(TAG_NAME);
							String brand =c.getString(TAG_BRAND);

							product_list.add(i + " ### " + uid + " ### " + brand + " ### " + name+ " ### " + "http://wwwfyp.cse.ust.hk:7117/Picture/upload/"+uid+"/"+uid+".jpg");


						}


					}
				} else if (!isOnline()){					
					String brand = "No_network";
					//String description = c.getString(TAG_description);

					new HashMap<String, String>();

					// adding each child node to HashMap key => value
					//map.put(TAG_upc, upc);
					//map.put(TAG_description, description);

					String uid = "0";
					String name = " ";
					product_list.add(1 + " ### " + uid + " ### " + brand + " ### " + name+ " ### " + R.drawable.ic_action_warning);
				} 				
				else {
					
					String brand = "Server_error";
					//String description = c.getString(TAG_description);

					new HashMap<String, String>();

					// adding each child node to HashMap key => value
					//map.put(TAG_upc, upc);
					//map.put(TAG_description, description);

					String uid = "0";
					String name = " ";	
					product_list.add(1 + " ### " + uid + " ### " + brand + " ### " + name+ " ### " + R.drawable.ic_action_warning);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			

			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			//			pDialog.dismiss();
			// updating UI from Background Thread

			runOnUiThread(new Runnable() {


				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					
					int temp=R.drawable.ic_action_picture;
					if (success!=1)
						temp =R.drawable.ic_action_warning;

					madapter = new MainArrayAdapter(AllProductsActivity.this, product_list,temp){					
						@Override
						public View getView(int position, View convertView,
								ViewGroup parent) {
							View view= super.getView(position, convertView, parent);
							if (view.findViewById(R.id.brand).equals("Server_error") || view.findViewById(R.id.brand).equals("No_network")){
								view.findViewById(R.id.report_price_button).setVisibility(8);
							}
							Button button=(Button) view.findViewById(R.id.report_price_button);
							button.setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									// TODO Auto-generated method stub
									if(!MainActivity.sharedpreferences.contains(Email)){
										Intent in2 = new Intent(getApplicationContext(),
												ChooseAccount.class);
										startActivityForResult(in2, 90);
										
									}
									else{
										Intent in = new Intent(AllProductsActivity.this,QuotationActivity.class);
										// sending upc to next activity
										in.putExtra(TAG_UID, (CharSequence) ((TextView)((View) v.getParent()).findViewById(R.id.uid)).getText().toString());
										in.putExtra(TAG_NAME, (CharSequence) ((TextView)((View) v.getParent()).findViewById(R.id.name)).getText().toString());
										startActivityForResult(in, 100);
									}
								}

							});
							return view;
						}

					};
					setListAdapter(madapter);
			}
		});
		((PullToRefreshListView) getListView()).onRefreshComplete();
		refreshing=false;
	}



}

}